#include <stdlib.h>
#include "mstring.h"

MString newString()
{
  MString ans;
  ans.ptr = 0;
  ans.size = 32;
  ans.data = (char*)malloc(sizeof(char) * ans.size);
  ans.data[0] = 0;
  return ans;
}

void freeString(const MString mstring)
{
  free(mstring.data);
}

void addChar(MString* mstring, const char ch)
{
  if (mstring->ptr == mstring->size - 1)
  {
    mstring->size <<= 1;
    mstring->data = realloc(mstring->data, mstring->size);
  }
  mstring->data[mstring->ptr++] = ch;
  mstring->data[mstring->ptr] = 0;
}

void addRawString(MString* mstring, const char* str)
{
  for (int i = 0; str[i] != 0; i++)
  {
    addChar(mstring, str[i]);
  }
}

void addMString(MString* mstring, const MString other)
{
  for (int i = 0; i < other.ptr; i++)
  {
    addChar(mstring, other.data[i]);
  }
}

MString numToMStr(unsigned long long num)
{
  MString ans = newString();
  while (num != 0)
  {
    addChar(&ans, num % 10 + 0x30);
    num /= 10;
  }
  for (int i = 0; i < ans.ptr / 2; i++)
  {
    char temp = ans.data[i];
    ans.data[i] = ans.data[ans.ptr - 1 - i];
    ans.data[ans.ptr - 1 - i] = temp;
  }
  return ans;
}

MString copyString(const MString mstring)
{
  MString ans;
  ans.ptr = mstring.ptr;
  ans.size = mstring.size;
  ans.data = (char*)malloc(sizeof(char) * ans.size);
  for (int i = 0; i < ans.ptr; i++)
  {
    ans.data[i] = mstring.data[i];
  }
  return ans;
}